package com.lengyu.vxminiprogram.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lengyu.vxminiprogram.common.AuthUtil;
import com.lengyu.vxminiprogram.common.BasePageParamDto;
import com.lengyu.vxminiprogram.common.HttpResultDto;
import com.lengyu.vxminiprogram.convert.IVotesConverter;
import com.lengyu.vxminiprogram.dto.VotesDto;
import com.lengyu.vxminiprogram.entity.VoteRecordUserView;
import com.lengyu.vxminiprogram.entity.Votes;
import com.lengyu.vxminiprogram.entity.VotesOptions;
import com.lengyu.vxminiprogram.entity.VotesRecords;
import com.lengyu.vxminiprogram.security.rest.dto.JwtUser;
import com.lengyu.vxminiprogram.service.IVoteRecordUserViewService;
import com.lengyu.vxminiprogram.service.IVotesOptionsService;
import com.lengyu.vxminiprogram.service.IVotesRecordsService;
import com.lengyu.vxminiprogram.service.IVotesService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuyu
 * @since 2025-02-24
 */
@RestController
@RequestMapping("/votes")
public class VotesController {
    private final static Logger logger = LoggerFactory.getLogger(VotesController.class);
    @Autowired
    IVotesService votesService;
    @Autowired
    IVotesConverter votesConverter;

    @Autowired
    IVotesOptionsService votesOptionsService;

    @Autowired
    IVotesRecordsService votesRecordsService;
    @Autowired
    IVoteRecordUserViewService recordUserViewService;


    @PostMapping(value="/save")
    public HttpResultDto<String> save(@RequestBody VotesDto votesDto){
        String id=votesDto.getId();
        Votes votes = votesConverter.dtoToEntity(votesDto);
        if(StringUtils.isBlank(votesDto.getId())){
            votesService.saveOrUpdate(votes);
            id=votes.getId();
            votesDto.getOptionsList().forEach(i->{
                i.setVoteId(votes.getId());
            });
            votesDto.setId(votes.getId());
            votesOptionsService.saveBatch(votesDto.getOptionsList());
        }
        else{
            //投票内容不可编辑，请删除后重新发起
        }

        return HttpResultDto.success(id);
    }

    @PostMapping(value="/page")
    public HttpResultDto<Page<VotesDto>> page(@RequestBody BasePageParamDto pageParamDto){
        //1：我发起的  2：我参与的
        int searchType = 1;

        QueryWrapper queryWrapper = new QueryWrapper();
        if(pageParamDto.getParamMapObj() != null){
            for(String key:pageParamDto.getParamMapObj().keySet()){
                if(StringUtils.isNotBlank(String.valueOf(pageParamDto.getParamMapObj().get(key)))){
                    if(key.equals("searchType")){
                        searchType = pageParamDto.getParamMapObj().getInteger(key);
                    }
                    else{
                        queryWrapper.like(key,pageParamDto.getParamMapObj().get(key));
                    }

                }
            }
        }
        if(searchType == 1 ){
            queryWrapper.eq("user_id", AuthUtil.getCurrentJwtUser().getId());
            logger.info(JSONObject.toJSONString(queryWrapper));
            queryWrapper.orderByDesc("create_time");

            Page<Votes> entityPage = votesService.page(new Page<>(pageParamDto.getPageIndex(), pageParamDto.getPageSize()),queryWrapper);
            Page<VotesDto> dtoPage = votesConverter.pageEntityToDto(entityPage);
            return HttpResultDto.success(dtoPage);
        }
        else if(searchType == 2){
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.like("user_id", AuthUtil.getCurrentJwtUser().getId());

            queryWrapper1.select("distinct vote_id,create_time");
            queryWrapper1.orderByDesc("create_time");
            Page<VotesRecords> recordPage =  votesRecordsService.page(new Page<>(pageParamDto.getPageIndex(), pageParamDto.getPageSize()),queryWrapper1);
            List<String> voteIdList = new ArrayList<>();
            if(recordPage.getRecords() != null && recordPage.getRecords().size() > 0){
                recordPage.getRecords().forEach(i->{
                    voteIdList.add(i.getVoteId());
                });
            }
            else{
                Page<VotesDto> pageDto = new Page<>();
                pageDto.setCurrent(recordPage.getCurrent());
                pageDto.setTotal(recordPage.getTotal());
                pageDto.setSize(pageDto.getSize());
                return HttpResultDto.success(pageDto);
            }
            queryWrapper.in("id",voteIdList);
            queryWrapper.orderByDesc("create_time");
            List<Votes> voteList =  votesService.list(queryWrapper);
            List<VotesDto> votesDtoList = votesConverter.listEntityToDto(voteList);
            Page<VotesDto> pageDto = new Page<>();
            pageDto.setCurrent(recordPage.getCurrent());
            pageDto.setRecords(votesDtoList);
            pageDto.setTotal(recordPage.getTotal());
            pageDto.setSize(recordPage.getSize());
            return HttpResultDto.success(pageDto);
        }
        else{
            return HttpResultDto.failed("searchType错误");
        }
    }

    @GetMapping(value="/detail")
    public HttpResultDto<VotesDto> detail(String id){
        Votes votes = votesService.getById(id);
        VotesDto votesDto = votesConverter.entityToDto(votes);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("vote_id",id);
        List<VotesOptions> optionsList = votesOptionsService.list(queryWrapper);
        List<VoteRecordUserView> recordsList = recordUserViewService.list(queryWrapper);
        votesDto.setOptionsList(optionsList);
        votesDto.setRecordsList(recordsList);

        return HttpResultDto.success(votesDto);
    }

    @PostMapping(value="/vote")
    public HttpResultDto<String> vote(@RequestBody JSONObject param){
        String voteId = param.getString("voteId");
        String optionId = param.getString("optionId");
        JwtUser user = AuthUtil.getCurrentJwtUser();
        if(user == null){
            return HttpResultDto.failed("请先登录");
        }
        else{
            VotesRecords votesRecords = new VotesRecords();
            votesRecords.initInsert();
            votesRecords.setVoteId(voteId);
            votesRecords.setUserId(user.getId());
            votesRecords.setUserName(user.getUsername());
            votesRecords.setVoteOptionId(optionId);
            votesRecordsService.save(votesRecords);

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("vote_id",voteId);
            queryWrapper.eq("id",optionId);
            VotesOptions votesOptions = votesOptionsService.getOne(queryWrapper,false);
            if(votesOptions!=null){
                queryWrapper = new QueryWrapper();
                queryWrapper.eq("vote_id",voteId);
                queryWrapper.eq("vote_option_id",optionId);
                int count = votesRecordsService.count(queryWrapper);
                votesOptions.setVoteCount(count);
                votesOptionsService.updateById(votesOptions);
            }

        }


        return HttpResultDto.success();
    }

}
